package com.qiyu.datasource.config;

import com.qiyu.datasource.enums.DatasourceConfigEnum;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @Author linhao
 * @Date created in 6:38 下午 2021/1/28
 */
@Slf4j
@Aspect
@Configuration
public class MultiDataSourceAspect {

    private final static String packAge = "execution(* com.qiyu.tech.id.builder.dao..*.*(..))";

    @Pointcut(packAge)
    public void pointCut() {
        log.info("multi datasource aspect");
    }

    @Resource
    private MultiDataSourceConfig multiDataSourceConfig;

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Class clazz = joinPoint.getSignature().getDeclaringType();
        String packageName = clazz.getPackage().getName();
        if (StringUtils.isEmpty(packageName)) {
            return;
        }
        System.out.println(packageName);
        DatasourceConfigEnum datasourceConfigEnum = multiDataSourceConfig.getDataSourcePackageMap().get(packageName);
        if (datasourceConfigEnum == null) {
            log.error("datasourceConfig is null");
            return;
        }
        DataSourceContextHolder.setDatabaseHolder(datasourceConfigEnum);
        System.out.println(datasourceConfigEnum);
        System.out.println(clazz.getPackage().getName());
        String name = joinPoint.getSignature().getName();
        log.info("before " + name);
    }

    @After("pointCut()")
    public void after() {
        log.info("after");
    }
}
